<template>
  <div class="scene-room-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            :disabled="handleDisabled(item)"
            @change="handlerSelectData(item)"
            @changeImg="changeImg"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import AddImg from '@/components/PopItems/add-img.vue'

export default {
  name: 'AddSceneRoom',
  mixins: [dictMixin],
  components: { AddImg },
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      areaMin: 0,
      areaMax: 10,
      formData: {},
      formList: [
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '所属楼栋',
          prop: 'sceneEdificeId',
          componentType: 'el-select',
          optionList: [],
          // selectPath: 'commonSelected',
          // selectParams: {
          //   code: 'SceneEdificeSelected'
          // },
          attrConfig: {
            placeholder: '请选择所属楼栋',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '所属楼层',
          prop: 'sceneFloorId',
          componentType: 'el-select',
          optionList: [],
          // selectPath: 'commonSelected',
          // selectParams: {
          //   code: 'SceneFloorSelected'
          // },
          attrConfig: {
            placeholder: '请选择所属楼层',
            filterable: true,
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '空间名称',
          prop: 'roomName',
          attrConfig: { placeholder: '请输入空间名称' }
        },
        {
          name: '建筑面积(m²)',
          componentType: 'el-input-number',
          prop: 'roomArea',
          attrConfig: {
            style: 'width:100%',
            controls: false,
            placeholder: '建筑面积(m²)'
          }
        },
        {},
        {
          name: '背景图',
          prop: 'backgroundImg',
          componentType: 'AddImg',
          attrConfig: { tip: '请上传jpg/png文件，且不超过5MB,建议尺寸1800px * 900px' }
        }
      ]
    }
  },
  computed: {
    handleDisabled() {
      return (item) => {
        // 编辑时这三个选项需禁用
        const arrList = ['sceneProjectId', 'sceneEdificeId', 'sceneFloorId']
        return arrList.includes(item.prop)
        // if(this.popConfig.disabled && arrList.includes(item.prop)){
        //   return true
        // }else{
        //   if (item.prop === 'sceneEdificeId') {
        //     return !this.formData.sceneProjectId
        //   } else if (item.prop === 'sceneFloorId') {
        //     return !this.formData.sceneEdificeId
        //   }
        // }
        // return false
      }
    },
    rules() {
      return {
        sceneProjectId: [
          { required: true, message: '请选择项目', trigger: 'blur' }
        ],
        sceneEdificeId: [
          { required: true, message: '请选择楼栋', trigger: 'blur' }
        ],
        sceneFloorId: [
          { required: true, message: '请选择楼层', trigger: 'blur' }
        ],
        roomName: [
          { required: true, message: '请输入空间名称', trigger: 'blur' }
        ],
        roomArea: [{ required: true, message: '请输入建筑面积', trigger: 'blur' },
          {
            min: this.areaMin,
            max: this.areaMax,
            type: 'integer',
            message: '建筑面积在' + this.areaMin + '~' + this.areaMax + '之间',
            trigger: 'blur'
          }]
      }
    }
  },
  created() {
    this.$api.sceneFloor.getAreaRange({
      sceneFloorId: this.requestParams.sceneFloorId,
      id: this.popData.id || ''
    }).then(res => {
      this.areaMin = res.data.minValue
      this.areaMax = res.data.maxValue
    })
  },
  watch: {
    popData: {
      async handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        if (data.backgroundImg != null) {
          this.formList[6].attrConfig.defaultFileList = [data.backgroundImg]
        }
        if (this.isAdd) {
          const floor = await this.$api.sceneFloor.detail(this.requestParams.sceneFloorId)
          this.$set(this.formData, 'sceneProjectId', floor.data.sceneProjectId)
          this.$set(this.formData, 'sceneEdificeId', floor.data.sceneEdificeId)
          this.$set(this.formData, 'sceneFloorId', this.requestParams.sceneFloorId)
        }
        this.$set(this.formData, 'id', data.id)
        this.commonSelected(1, {
          code: 'SceneEdificeSelected',
          param: data.sceneProjectId
        })
        this.commonSelected(2, {
          code: 'SceneFloorSelected',
          param: data.sceneEdificeId
        })
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    changeImg(key, value) {
      this.$set(this.formData, 'backgroundImgFile', value)
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'sceneProjectId') {
        if (this.formData.sceneEdificeId) {
          this.formData.sceneEdificeId = ''
        }
        this.commonSelected(1, {
          code: 'SceneEdificeSelected',
          param: this.formData.sceneProjectId
        })
      } else if (config.prop === 'sceneEdificeId') {
        if (this.formData.sceneFloorId) {
          this.formData.sceneFloorId = ''
        }
        this.commonSelected(2, {
          code: 'SceneFloorSelected',
          param: this.formData.sceneEdificeId
        })
      }
    },
    /**
     * 查询联动数据
     */
    commonSelected(idx, param) {
      this.$api.commonSelected(param).then((res) => {
        this.formList[idx].optionList = res.data.map((item) => ({
          ...item,
          name: item.label,
          code: item.value
        }))
      })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.formData.backgroundImgFile) {
            const formData = new FormData()
            formData.append('file', this.formData.backgroundImgFile.raw)
            const urlRes = await this.$api.fileManage.baseUploadData(
              '/energy-carbon/grass-file/file/upload',
              formData
            )
            if (Number(urlRes.code) === 1000) {
              params.backgroundImg = urlRes.data
            }
          }
          const res = await this.$api.sceneRoom[this.isAdd ? 'add' : 'update'](
            params
          )
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'scene-room-add')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.scene-room-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: 50%;

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
